<template>
  <div>
    <PageTools>
      <template #left>
        <el-alert
          :title="`当前共有${total}条记录`"
          type="info"
          show-icon
          :closable="false"
        />
      </template>
      <template>
        <el-button size="small" type="danger" @click="exportExcel">普通excel导出</el-button>
        <el-button size="small" type="warning">复杂excel导出</el-button>
        <el-button size="small" type="success" @click="$router.push('/import')">excel导入</el-button>
        <el-button v-if="checkPermission('POINT-USER-ADD')" size="small" type="primary" @click="show=true">新增员工</el-button>
        <el-button v-permission="'POINT-USER-ADD'" size="small" type="primary" @click="show=true">新增员工</el-button>
      </template>
    </PageTools>
    <el-card style="margin:20px;">
      <el-table :data="rows" border>
        <el-table-column label="序号" type="index" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="头像">
          <template #default="{row}">
            <img v-imgerror :src="row.staffPhoto" style="width:60px;height:60px;" alt="" @click="showEwm(row.staffPhoto)">
          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="mobile" />
        <el-table-column label="工号" prop="workNumber" />
        <el-table-column label="聘用形式" prop="formOfEmployment">
          <template #default="{row}">
            {{ row.formOfEmployment | form }}
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间" prop="timeOfEntry" sortable />
        <el-table-column label="账户状态" prop="enableState">
          <template #default="{row}">
            <el-switch :value="row.enableState" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280px">
          <template #default="{row}">
            <el-button type="text" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
            <el-button type="text">转正</el-button>
            <el-button type="text">调岗</el-button>
            <el-button type="text">离职</el-button>
            <el-button type="text" @click="showRole(row.id)">角色</el-button>
            <el-button type="text" disabled>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:right;margin-top:20px">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="params.size"
          @current-change="change"
        />
      </div>

    </el-card>
    <!-- $event如果是在原生的标签上，它代表的是事件对象 如果是在组件上，代表的是子传给父的值 -->
    <!-- v-model可以实现父子之间双向通信，有缺点只能有一个，所以sync诞生了 -->
    <!-- sync修饰符是一个语法糖
    自定义事件是固定写法 @update:属性名
    :msg.sync="msg"等价于 :msg="msg" @update:msg="msg=$event" -->
    <!-- <AddEmployee :dialog-visible="show" @update:dialogVisible="show=$event" /> -->
    <AddEmployee :dialog-visible.sync="show" />
    <el-dialog title="二维码" :visible.sync="show1" width="20%">
      <canvas ref="canvas" />
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="roleVisible"
      width="50%"
    >
      <el-checkbox-group v-model="checkedRoleList">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from 'qrcode'
import { getEmployeeList } from '@/api/employees'
import AddEmployee from './components/add-employee.vue'
import { getRoleList } from '@/api/setting'
import { getUserDetailById, assignRoleToUser } from '@/api/user'
export default {
  name: 'Employees',
  components: {
    AddEmployee
  },
  data() {
    return {
      params: {
        page: 1,
        size: 10
      },
      rows: [],
      total: null,
      show: false,
      show1: false,
      roleVisible: false,
      roleList: [],
      checkedRoleList: [],
      id: null
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.params)
      this.rows = rows
      this.total = total
      console.log(rows)
    },
    change(current) {
      this.params.page = current
      this.getEmployeeList()
    },
    async exportExcel() {
      // 把所有的员工全部拿到
      const { rows } = await getEmployeeList({ page: 1, size: 9999999999999 })
      // rows.forEach(item => {
      //   console.log(Object.values(item))
      // })
      // rows变成二维数组
      const arr = []// 大的二维
      rows.forEach(item => {
        const arr1 = []
        arr1.push(item.username)
        arr1.push(item.mobile)
        arr1.push(item.timeOfEntry)
        arr1.push(item.formOfEmployment)
        arr1.push(item.correctionTime)
        arr1.push(item.workNumber)
        arr1.push(item.departmentName)
        arr.push(arr1)
      })
      console.log(arr)

      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['姓名', '手机号', '聘用形式', '入职日期', '转正日期', '工号', '部门']
        const data = arr
        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    showEwm(url) {
      console.log(url)
      this.show1 = true// 可以让对话框打开，但是这个数据变了，视图的更新的是异步的 nextTick有一个特点 回调函数是在视图更新之后才会执行
      this.$nextTick(() => {
        const canvas = this.$refs.canvas
        // alt + a
        var opts = {
          errorCorrectionLevel: 'H',
          type: 'image/jpeg',
          quality: 0.3,
          margin: 1,
          color: {
            dark: '#010599FF',
            light: '#FFBF60FF'
          }
        }
        QRCode.toCanvas(canvas, url, opts, function(error) {
          if (error) console.error(error)
          console.log('success!')
        })
      })
    },
    async showRole(id) {
      this.id = id
      const res = await getRoleList({ page: 1, pagesize: 9999 })
      // console.log(res)
      // console.log(id)
      this.roleList = res.rows

      const res1 = await getUserDetailById(id)
      // console.log(res1)
      this.checkedRoleList = res1.roleIds

      this.roleVisible = true// 一般会把显示对话框放最后一行
    },
    async saveRole() {
      await assignRoleToUser({ roleIds: this.checkedRoleList, id: this.id })
      this.$message.success('为员工分配权限成功')
      this.roleVisible = false
    }

  }
}
</script>

<style scoped lang='scss'></style>
